/*
 * Server.cpp
 *
 *  Created on: Aug 11, 2012
 *      Author: nam20485
 */

#include "Server.h"
#include "Arduino.h"

Server::Server(ServerReceiveHandler m_pfnReceiveHandler)
	: m_ulNextConnection(0)
	, m_pfnReceiveHandler(0)
{
	memset(m_apConnections, 0, sizeof(Connection*)*MAX_CONNECTIONS);
}

Server::~Server()
{
	for (unsigned long l = 0; l < MAX_CONNECTIONS; l++)
	{
		if (m_apConnections[l])
		{
			delete m_apConnections[l];
			m_apConnections[l] = 0;
		}
	}
}

Connection::ID Server::Connect(/*const*/ IConnector& connector)
{
	if (m_ulNextConnection < MAX_CONNECTIONS)
	{
		Connection::ID lNewID = static_cast<Connection::ID>(m_ulNextConnection);
		Connection * pConnection = new Connection(	lNewID,
													connector,
													reinterpret_cast<Connection::ConnectionReceiveHandler>( &Server::OnConnectionReceive));
		if (pConnection->Connect())
		{
			m_apConnections[m_ulNextConnection] = pConnection;
			m_ulNextConnection++;
		}
	}
	return -1;
}

bool Server::Shutdown()
{
	// disconnect all connections
}

void Server::OnConnectionReceive(Connection::ID lClientID, const Message& message)
{
	if (m_pfnReceiveHandler)
	{
		m_pfnReceiveHandler(lClientID, message);
	}
}




